package ie.timalb.chess.main.core.temp;


import java.util.HashMap;
import java.util.Iterator;

import ie.timalb.chess.main.core.exceptions.SquareOutOfRangeException;
import ie.timalb.chess.main.core.movement.Location;
import ie.timalb.chess.main.core.movement.Route;
import ie.timalb.chess.main.core.pieces.Piece;
import ie.timalb.chess.main.core.squares.Square;
import ie.timalb.chess.main.core.squares.iSquareContent;
import ie.timalb.chess.main.core.squares.SquareWithPiece;
import ie.timalb.chess.main.core.squares.SquareWithoutPiece;

public class Squares {
	private HashMap<Location, Square>  _squares;
		
	public Squares() {
		_squares = new HashMap<Location, Square> ();		
	}

	public Squares(Squares squares) {
		Iterator <Square> it = squares.getUnorderedIterator();
		Square square;
		while (it.hasNext()){
			square = it.next();
			add(square);
		}
	}

	public Iterator<Square> getUnorderedIterator() {
		return getSquares().values().iterator();
	}

	public boolean containsRoute(Route route) {
		boolean result = false;
		Square square = null;
		Iterator <Square> it = route.iterator();
		
		while (it.hasNext())
		{
			square = it.next();
			if (contains(square))
			{
				result = true;
				break;
			}
		}
		
		return result;
	}

	public void add(Square square) {
		getSquares().put(square.getLocation(), square);		
	}

	private HashMap<Location, Square> getSquares() {
		return _squares;
	}

	public Square getSquare(Location location) throws SquareOutOfRangeException {
		Square square = getSquares().get(location);
		if (square == null) { throw new SquareOutOfRangeException(); }
		return square;
	}

	public void createEmptySquare(int currentCoordX, int currentCoordY)
		throws SquareOutOfRangeException
	{
		Location location = new Location (currentCoordX, currentCoordY);
		Square square = new SquareWithoutPiece (location);
		add(square);
	}
	
	public void createPopulatedSquare(iSquareContent content, int currentCoordX, int currentCoordY)
	throws SquareOutOfRangeException
	{
		Location location = new Location (currentCoordX, currentCoordY);
		Square square = new SquareWithPiece (piece, location);
		add (square);
	}

	public int getSquareCount() {
		return getSquares().size();
	}

	public boolean contains(Square currentRouteSquare) {		
		return getSquares().containsValue(currentRouteSquare);
	}

	public void addPiece(Piece piece, Location location)
	throws SquareOutOfRangeException {
		Square currentSquare = getSquare(location);
		if (currentSquare.isOccupied())
		{
			currentSquare.setPiece (piece);
		}else
		{
			getSquares().remove(currentSquare);
			createPopulatedSquare(piece, location.getXCoordinate(), location.getYCoordinate());			
		}		
	}
}
